<template>
  <!-- 考勤-部门考勤 -->
  <div class="swipe_details">
    <el-form :inline="true" :model="elform" size="mini">
      <myTime @handleGetTime="handleGetTime" :isTime="false"></myTime>
      <el-form-item label="部门:">
        <el-select
          v-model="departmentGuid"
          placeholder="请选择"
          size="mini"
          clearable
          @change="selectdepartment"
          style="width: 100%"
          multiple
          filterable
        >
          <el-option
            v-for="item in departmentoptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="考勤班次" prop="attendanceRuleGuid">
        <el-select
          v-model="attendanceRuleItem"
          placeholder="请选择"
          filterable
          clearable
          style="width:100%"
          size="mini"
        >
          <el-option
            v-for="item in attendanceRuleOption"
            :key="item.ruleFrameGuid"
            :label="item.ruleFrameName"
            :value="item.ruleFrameGuid+','+item.ruleFrameName+','+item.type"
          ></el-option>
        </el-select>
      </el-form-item>

      <!-- <el-form-item label="姓名:">
        <el-input v-model="userName" placeholder="姓名" size="mini" clearable style="width: 120px"></el-input>
      </el-form-item>
      <el-form-item label="编号:">
        <el-input v-model="userNumber" placeholder="编号" size="mini" clearable style="width: 120px"></el-input>
      </el-form-item>-->

      <el-form-item class="searchmarigin">
        <el-button type="primary" @click="onSubmit" size="mini" icon="el-icon-search">查询</el-button>
        <el-button type="primary" @click="onExport" size="mini" icon="el-icon-document-copy">导出</el-button>
        <el-button type="primary" @click="onExport('print')" size="mini" icon="el-icon-printer">打印</el-button>
        <el-popover width="500" placement="top" trigger="click">
          <el-row>
            <el-row>
              <el-col :span="6" v-for="item in Object.keys(formThead)" :key="item">
                <el-checkbox
                  :label="formThead[item].label"
                  v-model="formThead[item].checked"
                  @change="checkboxChanged()"
                ></el-checkbox>
              </el-col>
            </el-row>
          </el-row>
          <el-button slot="reference" size="mini" type="primary" icon="el-icon-edit-outline">自定义</el-button>
        </el-popover>
      </el-form-item>
    </el-form>
    <div class="tablemain">
      <el-table
        v-loading="loading"
        :data="detailslist"
        ref="table"
        border
        highlight-current-row
        style="width: 100%"
        :header-cell-style="headFirst"
        :cell-style="
          detailsTotal ? (res) => headFirst_col(res, detailslist) : (res) => headFirst_col(res, [])
        "
      >
        <template v-for="item in Object.keys(formThead)">
          <el-table-column
            :key="item"
            :prop="formThead[item].prop"
            :label="formThead[item].label"
            v-if="formThead[item].checked"
          ></el-table-column>
        </template>
      </el-table>
      <div class="page">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChangepage"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="recordCount"
        ></el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
export default {
  data() {
    return {
      filename: '部门考勤报表',
      // 考勤班次
      attendanceRuleItem: '',
      // 考勤班次
      attendanceRuleOption: [],
      departmentoptions: [],
      departmentGuid: [],
      groupingoption: [],
      groupingGuid: [],
      userName: '',
      cardNumber: '',
      userNumber: '',
      datetime: '',
      time: [],
      chargingType: [],

      elform: {},
      // 是否包含非确定交易
      includeNoSuccess: false,
      //
      detailslist: [],
      loading: false,
      pageNum: 1,
      pageSize: 20,
      currentPage: 1,
      recordCount: 0,
      searchInfo: {},
      formThead: {
        departmentName: {
          label: '部门',
          prop: 'departmentName',
          checked: true
        },
        // attendanceUserCount: {
        //   label: '参与考勤人数',
        //   prop: 'attendanceUserCount',
        //   checked: true
        // },
        normalCount: {
          label: '正常次数',
          prop: 'normalCount',
          checked: true
        },
        lateCount: {
          label: '迟到次数',
          prop: 'lateCount',
          checked: true
        },
        leaveEarlyCount: {
          label: '早退次数',
          prop: 'leaveEarlyCount',
          checked: true
        },
        missCardCount: {
          label: '漏刷卡次数',
          prop: 'missCardCount',
          checked: true
        },
        absentFromWorkCount: {
          label: '缺勤次数',
          prop: 'absentFromWorkCount',
          checked: true
        },
        dayNumber: { label: '统计天数', prop: 'dayNumber', checked: true }
      },
      //导出数据
      detailslistExportlist: [],

      //汇总合计
      totalto: false,
      detailsTotal: null
    }
  },
  created() {
    this.datetime = [this.getNowTime('yy-mm-dd'), this.getNowTime('yy-mm-dd')]
    this.time = ['00:00:00', '23:59:59']
    this.getRule()
  },
  mounted() {
    this.departmentselectlist()
    this.unitgroup()
  },
  filters: {},
  computed: {
    changeschoolid: {
      get() {
        return this.$store.state.user.changeschoolid
      }
    }
  },
  methods: {
    /**获取时间 */
    handleGetTime(val) {
      console.log(val)
      this.datetime = [val.startDate, val.endDate]
      this.time = [val.startTime, val.endTime]
      this.radio = val.timeradio
    },

    // 重新渲染表格
    checkboxChanged() {
      this.$nextTick(() => {
        this.$refs['table'].doLayout()
      })
    },
    // 获取考勤班次信息
    getAttendance() {
      let arr = this.attendanceRuleItem.split(',')
      let ruleFrameGuid = arr[0]
      let ruleFrameName = arr[1]
      let type = arr[2]
      let ruleguid_type = type == 'rule' ? 'ruleGuid' : 'frameGuid'

      let rulename_type =
        type == 'rule' ? 'attendanceRuleName' : 'attendanceFrameName'
      return {
        ruleFrameGuid,
        ruleFrameName,
        type,
        ruleguid_type,
        rulename_type
      }
    },
    // 获取考勤班次
    getRule() {
      this.$http({
        url: this.$http.adornUrl('/attendance/attendance-rule-and-frame'),
        method: 'post',
        data: this.$http.adornData({
          messageContent: {
            unitGuid: this.changeschoolid
          },
          messageType: 0
        })
      }).then(({ data }) => {
        if (data.messageCode == 200) {
          this.attendanceRuleOption = data.messageContent || []
        } else {
          this.$message.error(data.errorMessage)
        }
      })
    },
    //合计查询
    searchtotal() {
      this.searchInfo.unitGuid = this.changeschoolid
      this.detailsTotal = null
      let _this = this
      _this.loading = true
      return new Promise(function(resolve, reject) {
        _this
          .$http({
            url: _this.$http.adornUrl(
              '/terminal/consume/consume-data-details-total'
            ),
            method: 'post',
            data: _this.$http.adornData({
              messageContent: _this.searchInfo,
              messageType: 0
            })
          })
          .then(({ data }) => {
            _this.loading = false
            if (data.messageCode == 200) {
              if (data.messageContent) {
                _this.detailsTotal = {
                  ...data.messageContent,
                  departmentName: '合计：',
                  newBalance: ''
                }
              }
              resolve(data.messageContent)
            } else {
              _this.$message.error(data.errorMessage)
              reject(data.errorMessage)
            }
          })
      })
    },
    //部门选择
    departmentselectlist() {
      this.departmentoptions = []
      this.$http({
        url: this.$http.adornUrl('/department/query-department-info'),
        method: 'post',
        data: this.$http.adornData({
          messageContent: {
            unitGuid: this.changeschoolid
          },
          messageType: 0
        })
      }).then(({ data }) => {
        if (data.messageCode == 200) {
          let Arr = data.messageContent
          for (var i = 0; i < Arr.length; i++) {
            let itemobj = {
              value: Arr[i].departmentGuid,
              label: Arr[i].departmentName
            }
            this.departmentoptions.push(itemobj)
          }
        } else {
          this.$message.error(data.errorMessage)
        }
      })
    },
    //单位分组查询
    unitgroup() {
      this.groupingoption = []
      this.$http({
        url: this.$http.adornUrl('/unit/unit-user-group-list'),
        method: 'post',
        data: this.$http.adornData({
          messageContent: this.changeschoolid,
          messageType: 0
        })
      }).then(({ data }) => {
        if (data.messageCode == 200) {
          let Arr = data.messageContent
          for (var i = 0; i < Arr.length; i++) {
            let itemobj = {
              value: Arr[i].groupGuid,
              label: Arr[i].groupName
            }
            this.groupingoption.push(itemobj)
          }
        } else {
          this.$message.error(data.errorMessage)
        }
      })
    },
    selectdepartment() {},
    // 查询
    async onSubmit() {
      this.pageNum = 1
      this.searchInfo = {}
      // 获取考勤班次
      // 获取当前选中到考勤班次信息
      const { ruleFrameGuid, ruleguid_type } = this.getAttendance()
      this.searchInfo[ruleguid_type] = ruleFrameGuid
      this.searchInfo.unitGuid = this.changeschoolid
      this.searchInfo.departmentGuidList = this.departmentGuid
      //   this.searchInfo.userName = this.userName
      //   this.searchInfo.cardNumber = this.cardNumber
      //   this.searchInfo.userNumber = this.userNumber
      //   this.searchInfo.groupGuidList = this.groupingGuid
      this.searchInfo.startDate = this.datetime[0]
      this.searchInfo.endDate = this.datetime[1]

      //   await this.searchtotal()
      this.detailspage()
    },
    //部门考勤分页查询
    detailspage() {
      this.loading = true
      this.searchInfo.unitGuid = this.changeschoolid
      this.$http({
        url: this.$http.adornUrl('/attendance/attendance-data-department-page'),
        method: 'post',
        data: this.$http.adornData({
          messageContent: {
            pageNum: this.pageNum,
            pageSize: this.pageSize,
            searchInfo: this.searchInfo
          },
          messageType: 0
        })
      }).then(({ data }) => {
        this.loading = false
        if (data.messageCode == 200) {
           if (
          data.messageContent.data.length == 0 ||
          data.messageContent.data == null
        ) {
          this.$message({
            message: '查询成功当前暂无数据',
            type: 'success'
          })
        }
          this.detailslist = data.messageContent.data || []
          this.recordCount = data.messageContent.recordCount
          this.currentPage = data.messageContent.pageNum
          //   if (this.detailslist != 0) {
          //     this.detailslist.push(this.detailsTotal)
          //   }
        } else {
          this.$message.error(data.errorMessage)
        }
      })
    },
    async onExport(type) {
      if (this.detailslist.length == 0) {
        this.$message({
          message: '请查询数据后,在进行此操作',
          type: 'warning'
        })
        return false
      }
      await this.outexecelinit()
      if (type == 'print') {
        this.printJS()
      } else {
        this.export2Excel()
      }
    },
    // 打印
    printJS() {
      let someJSONdata = this.detailslistExportlist
      const title = '部门考勤报表'
      this.unitName = sessionStorage.getItem('unitName')
      const properties = []
      // 拿到数据,filterValArr为数据值，tHeader为数据标题，一一对应
      for (let key in this.formThead) {
        if (this.formThead[key].checked) {
          properties.push({
            displayName: this.formThead[key].label,
            field: this.formThead[key].prop
          })
        }
      }
      // 打印
      this.$printJS({
        // 眉头
        documentTitle: `${this.unitName}`,
        /**
         * 获取表头的信息
         * @param {*} title 表名
         * @param {*} unitName 单位
         * @param {*} time 时间
         */
        header: this.printHeader(
          title,
          this.unitName,
          `${this.searchInfo.startDate} 至 ${this.searchInfo.endDate}`
        ),
        printable: someJSONdata,
        properties: properties,
        type: 'json',
        // 是否每页都显示头部
        // repeatTableHeader:false,
        headerRow: 1,
        /**
         * 获取页脚的信息
         * @param {*} loginName 制表人：
         * @param {*} time 时间
         */
        endPage: this.printFloor(
          sessionStorage.getItem('username'),
          this.getNowTime('yy-mm-dd hh:mm:ss')
        ),
        //  获取页脚的信息样式
        style: this.printFloorStyle()
      })
    },
    //部门考勤导出数据
    outexecelinit() {
      let _this = this
      return new Promise(function(resolve, reject) {
        _this
          .$http({
            url: _this.$http.adornUrl(
              '/attendance/attendance-data-department-page'
            ),
            method: 'post',
            data: _this.$http.adornData({
              messageContent: {
                pageNum: 1,
                pageSize: _this.recordCount,
                searchInfo: _this.searchInfo
              },
              messageType: 0
            })
          })
          .then(({ data }) => {
            if (data.messageCode == 200) {
              _this.detailslistExportlist = data.messageContent.data
              //   _this.detailslistExportlist.push({ ..._this.detailsTotal })

              resolve(_this.detailslistExportlist)
            } else {
              reject(data.errorMessage)
              _this.$message.error(data.errorMessage)
            }
          })
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },
    export2Excel() {
      const nowtime = this.getimeto()
      require.ensure([], () => {
        const multiHeader = []
        const multiHeader2 = []
        const merges = []
        const { export_json_to_excel } = require('../../excel/Export2Excel')
        // tHeaderarr.push('部门名称')

        let tHeader = []
        let filterValArr = []
        for (let key in this.formThead) {
          if (this.formThead[key].checked) {
            tHeader.push(this.formThead[key].label)
            filterValArr.push(this.formThead[key].prop)
          }
        }
        const filterVal = filterValArr

        const list = this.detailslistExportlist
        const data = this.formatJson(filterVal, list)
        export_json_to_excel({
          multiHeader, //这里是第一行的表头
          multiHeader2, //这里是第二行的表头
          header: tHeader, //这里应该是算第三行的表头
          data,
          merges,
          filename: this.filename + nowtime
        })
      })
    },

    handleSizeChange(val) {
      this.pageSize = val
      this.detailspage()
    },
    handleCurrentChangepage(val) {
      this.pageNum = val
      this.detailspage()
    }
  }
}
</script>

<style lang="scss" scoped>
.swipe_details {
  padding: 10px;
  /deep/.el-form-item--mini.el-form-item,
  .el-form-item--small.el-form-item {
    margin-bottom: 5px;
  }
  //滚动条的宽度
  ::-webkit-scrollbar {
    width: 10px;
    height: 10px;
  }

  //滚动条的滑块
  ::-webkit-scrollbar-thumb {
    background-color: #a1a3a9;
    border-radius: 3px;
  }

  .el-table__row .el-table__row--level-1 {
    background-color: #e5e9f2;
  }
  .demo-form-inline,
  .demo-form-inline1 {
    height: 50px;
    width: 1234px;
    display: flex;
    /deep/.el-form-item__label {
      padding-right: 5px;
    }
    .el-form-item {
      margin-bottom: 0px;
    }
    .el-date-editor.el-input,
    .el-date-editor.el-input__inner {
      width: 350px;
    }
  }
  .demo-form-inline1 {
    border-bottom: 1px solid #e5e9f2;
    .searchmarigin {
      margin-left: 20px;
    }
  }
  .page {
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>